package com.example.t_test_20210621_ArrayToCollection;


import java.util.*;

/**
 * hashSet去重原理：先判断hashCode是否相等，在判断equals方法，根据业务规则通过属性进行方法重写。
 * hashCode为Object中的方法，因此所有对象都存在hashCode，其与地址存在一对一对应关系，可以当做索引。
 * 例：地址当作：火车座位 座位号当作：hashCode
 */
class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

public class HashSetTest {

    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<>();
        Person person1 = new Person("张三", 26);
        Person person2 = new Person("张三", 26);
        Person person3 = new Person("李四", 27);
        Person person4 = new Person("王五", 28);
        set.add(person1);
        set.add(person2);
        set.add(person3);
        set.add(person4);
        System.out.println(set);

        /**
         * 获取1-20随机数，获取10个，不重复
         */

        Random random = new Random();
        HashSet<Integer> hashSet = new HashSet<>();
        while(hashSet.size() < 10){
            int i = random.nextInt(20) + 1;
            hashSet.add(i);
        }
        System.out.println(hashSet);

        /**
         * 从键盘输入一串字符串，去重 aaabbbccc ，返回abc
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一串字符串.....");
        String next = scanner.nextLine();
        char[] chars = next.toCharArray();
        LinkedHashSet<Character> hashSet1 = new LinkedHashSet<>();
        for (char c:chars) {
            hashSet1.add(c);
        }
        Iterator<Character> iterator = hashSet1.iterator();
        StringBuilder result = new StringBuilder();
        while (iterator.hasNext()){
            result.append(iterator.next());
        }
        System.out.println("result="+result);
    }


}
